package utils

import java.text.SimpleDateFormat
import java.util.logging.ConsoleHandler
import java.util.logging.Formatter
import java.util.logging.Handler
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
import java.util.logging.StreamHandler

/**
 * Created by midnite on 14/11/27.
 */
class LogFactory {

	private static Level logLevel = Level.FINEST

	static Logger getLogger(Class<?> clazz) {
		Logger log = Logger.getLogger(clazz.name)
		def defaultHandler = new ConsoleHandler()
		defaultHandler.setFormatter(new LogFormatter())
		defaultHandler.setLevel(logLevel)
		defaultHandler.setEncoding("UTF-8")
		log.addHandler(defaultHandler)
		log.setLevel(logLevel)
		log
	}

	static class LogFormatter extends Formatter {
		@Override
		String format(LogRecord record) {
			def time = Calendar.getInstance()
			time.setTimeInMillis(record.millis)
			def gap = ""
			(7 - record.level.name.length()).times { gap += " " }
			"${ -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(time.getTime())} " +
					"${record.level.name.toUpperCase()} " + gap +
					"[${record.loggerName}] > " +
					formatMessage(record) + "\n\r"
		}
	}
}
